package mianshi.consumer;

import lombok.SneakyThrows;

import java.util.Queue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Consumer implements Runnable {

    private Queue<String> msg;

    private int maxSize;

    private Lock lock;

    private Condition condition;

    public Consumer(Queue<String> msg, int maxSize, Lock lock, Condition condition) {
        this.msg = msg;
        this.maxSize = maxSize;
        this.lock = lock;
        this.condition = condition;
    }

    @SneakyThrows
    @Override
    public void run() {
        while (true) {
            lock.lock();
            while (msg.isEmpty()) {
                condition.await();
            }
            Thread.sleep(TimeUnit.MILLISECONDS.toMillis(500));
            String item = msg.remove();
            System.out.println("消费者：" + item);
            condition.signal();

            lock.unlock();
        }
    }
}
